package cog.support.util.stringmatching.patter;

import cog.support.util.common.StringKit;
import cog.support.util.stringmatching.StringMatching;
import cog.support.util.stringmatching.StringMatchingModel;

import java.time.LocalDateTime;


/**
 * java IndexOf 方法的实现方式
 *
 * @author 陈杰
 * @since 2016年9月14日 03:45:44
 * @version v0.1
 *
 * Copyright ChenJie(chenjie_java@aliyun.com)
 */
public class StringIndexPattern<T> implements StringMatching<T>{
	private static final String splitString = "%";

	private String[] patternChars;

	private int hitcount;

	private LocalDateTime lastHitTime;
	
	private T object;

	private char firstChar;

	private char endChar;

	private int firstPattern;

	private int endPattern;

	public StringIndexPattern(String pattern,T t){
		this.object = t;
		this.initChars(pattern);
	}
	
	private void initChars(String patternStrIn){
		String patternStr = patternStrIn.replaceAll("\\(.\\)+","%");
		patternStr= patternStr.replaceAll("%+","%");
		String[] strArray = patternStr.split("%");
		int patterLength = 0;

		for(String str : strArray){
			if(StringKit.isNotEmpty(str)) patterLength ++ ;
		}
		this.patternChars = new String[patterLength];

		patterLength = 0;
		for (String str : strArray) {
			if (StringKit.isNotEmpty(str)) {
				this.patternChars[patterLength++] = str;
			}
		}

		this.firstPattern = patternStr.startsWith("%") ? 0 : 1;
		this.firstChar = patternStr.charAt(0);

		this.endPattern =  patternStr.endsWith("%") ? 0 : 1;
		this.endChar = patternStr.charAt(patternStr.length() -1) ;

	}
	
	public StringMatchingModel<T> find(String sources){
		//首位匹配
		if(this.firstPattern > 0 &&
				sources.charAt(0) != this.firstChar ) return null;

		//末尾匹配
		if(this.endPattern > 0 &&
				sources.charAt(sources.length() - 1) != this.endChar) return null;

		//顺序匹配
		int lastIndex = 0;
		for (String patternChar : patternChars) {
			int fs = sources.indexOf(patternChar, lastIndex);
			if (fs < 0) return null;
			else lastIndex = fs;
		}

		this.hitcount ++ ;
		this.lastHitTime = LocalDateTime.now();
		return new StringMatchingModel<>(this.object);
	}

	@Override
	public StringMatchingModel<T> findReturn(String sources) {
		return this.find(sources);
	}

	@Override
	public LocalDateTime getLastHitTime() {
		return this.lastHitTime;
	}

	@Override
	public int clearHitCount() {
		int returnCont = this.hitcount;
		this.hitcount = 0;
		return returnCont;
	}

	@Override
	public T getObject() {
		return this.object;
	}

	public String[] getPatternChars() {
		return patternChars;
	}

	public void setPatternChars(String[] patternChars) {
		this.patternChars = patternChars;
	}

	public int getFirstPattern() {
		return firstPattern;
	}

	public void setFirstPattern(int firstPattern) {
		this.firstPattern = firstPattern;
	}
}
